package manager

import (
	"fmt"
	"game-server/interfaces"
	"game-server/message"
	"sync"
)

// ClientManager 客户端管理器
type ClientManager struct {
	clients      map[uint]interfaces.IClient
	clientsMutex sync.RWMutex
}

// NewClientManager 创建新的客户端管理器
func NewClientManager() *ClientManager {
	return &ClientManager{
		clients: make(map[uint]interfaces.IClient),
	}
}

// GlobalClientManager 全局客户端管理器实例
var GlobalClientManager = NewClientManager()

// AddClient 添加客户端
func (cm *ClientManager) AddClient(userId uint, c interfaces.IClient) {
	cm.clientsMutex.Lock()
	cm.clients[userId] = c
	cm.clientsMutex.Unlock()
}

// RemoveClient 移除客户端
func (cm *ClientManager) RemoveClient(userId uint) {
	cm.clientsMutex.Lock()
	delete(cm.clients, userId)
	cm.clientsMutex.Unlock()
}

// BroadcastMessage 广播消息给所有客户端
func (cm *ClientManager) BroadcastMessage(data []byte) {
	cm.clientsMutex.RLock()
	for _, client := range cm.clients {
		err := client.SendMessage(data)
		if err != nil {
			return
		}
	}
	cm.clientsMutex.RUnlock()
}

// SendToClient 发送消息给指定客户端
func (cm *ClientManager) SendToClient(userID uint, msg message.IMessage) error {
	cm.clientsMutex.RLock()
	client, exists := cm.clients[userID]
	cm.clientsMutex.RUnlock()

	if !exists {
		return fmt.Errorf("客户端 %d 不存在", userID)
	}

	data, err := message.GlobalCoder.Encode(msg)
	if err != nil {
		return fmt.Errorf("消息编码失败: %v", err)
	}

	return client.SendMessage(data)
}
